package com.kld.third.service.impl.cardcore;

import com.alibaba.dubbo.config.annotation.Service;
import com.kld.common.cardcore.HsmUtil;
import com.kld.common.cardcore.WebServerUtil;
import com.kld.common.util.XmlUtils;
import com.kld.third.cardcore.api.ICardCoreService;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaohe on 2016/3/29.
 */
@Service
public class CardCoreServiceImpl implements ICardCoreService {
    private Logger logger = LoggerFactory.getLogger(CardCoreServiceImpl.class);
    //--------------------------------------------电子卡接口
    @Override
    public Map<String, Object> electronicCard(String url, String operationName, Map<String, Object> map) {
        WebServerUtil webServerUtil=new WebServerUtil();
        XmlUtils xmlUtils=new XmlUtils();
        String reqXml=xmlUtils.getXmlInfo(map);
        String result=webServerUtil.querCardCore(url, operationName, reqXml);
        Map<String,Object> map1=new HashMap<String,Object>();
        try {
            map1= XmlUtils.xmlBody2map(result, "output");

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map1;
    }
    //---------------------------------------------卡积分系统
    @Override
    public Map<String, Object> integralCard(String url, String operationName, Map<String, Object> map) {
        String cardAsn=(String)map.get("cardAsn");
        String mac="";
        String reqXml="";
        WebServerUtil webServerUtil=new WebServerUtil();
        //查询接口不需要经行加密
        if(!"getPointAccount".equals(operationName)||!"getLoyTradeInfo".equals(operationName)) {
            //map转换成xml为接下来的加密做准备
            XmlUtils xmlUtils = new XmlUtils();
            reqXml = xmlUtils.getXmlInfo(map, operationName);
            //加密
            HsmUtil hsmUtil = new HsmUtil();
            int i = -1;
            i = hsmUtil.HSM_INI(); //初始化加密机
            if (i == 0 || i == 1 || i == 2) { //连接成功
                logger.info("生成Mac参数=================" + reqXml);
                mac = hsmUtil.HSM_GenerateMAC(reqXml.length(), reqXml, cardAsn.substring(cardAsn.length() - 8));
            }
            map.put("MAC", mac);
            reqXml = xmlUtils.getXmlInfo(map, operationName);
        }
        //  请求接口
        String result=webServerUtil.querCardCore(url, operationName, reqXml);
        Map<String,Object> map1=new HashMap<String,Object>();
        Map<String,Object> map2=new HashMap<String,Object>();
        try {
//            map1= XmlUtils.xmlBody2map(result, "/DATA");
//            map2=XmlUtils.xmlBody2map(result, "/DATA/CONSSET");
//            map1.putAll(map2);
            map1=XmlUtils.xmlBody1map(result);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map1;
    }





}
